package com.ternnetwork.clustersyn.util;

import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.util.List;
import org.apache.log4j.Logger;
import com.ternnetwork.clustersyn.model.AppInstance;
import com.ternnetwork.clustersyn.model.Cluster;
import com.ternnetwork.clustersyn.model.ServerNode;

public class ClusterUtil {
	private static final Logger log = Logger.getLogger(ClusterUtil.class);
	
public static String getFtpHomeDirectoryBylocalFilePath(String localFilePath,long serverNodeId){
	Cluster cluster=ClusterConfigUtil.getCluster();
	List<ServerNode> serverNodeList=cluster.getServerNodeList();
	for(ServerNode serverNode:serverNodeList){
		if(serverNode.getId()==serverNodeId){
			  List<AppInstance> appInstanceList=serverNode.getAppInstanceList();
			   for(AppInstance appInstance:appInstanceList){
				   if(localFilePath.contains(appInstance.getFtpHomeDirectory()+"/")){
					   return appInstance.getFtpHomeDirectory();
				   }
			   }
		}
		 
	}
	return null;
}	
	
public static void saveToCluster(String localFilePath) throws SocketException, IOException{
	
	Cluster cluster=ClusterConfigUtil.getCluster();
	List<ServerNode> serverNodeList=cluster.getServerNodeList();
    String currentInstanceFtpHomeDirectory=getFtpHomeDirectoryBylocalFilePath(localFilePath,cluster.getCurrentServerNodeId())+"/";
    log.info("localFilePath:"+localFilePath);
    log.info("currentInstanceFtpHomeDirectory:"+currentInstanceFtpHomeDirectory);
    
    String relativeFilePath=localFilePath.replace(currentInstanceFtpHomeDirectory,"");
    log.info("temp relativeFilePath "+relativeFilePath);
    String fileName=relativeFilePath.substring( relativeFilePath.lastIndexOf("/")+1,relativeFilePath.length());
	
    relativeFilePath=relativeFilePath.substring(0,relativeFilePath.lastIndexOf("/"));
	
    for(ServerNode serverNode:serverNodeList){
		   log.info("开始与主机"+serverNode.getIp()+"通讯"); 
		   List<AppInstance> appInstanceList=serverNode.getAppInstanceList();
		   for(AppInstance appInstance:appInstanceList){
			   if(serverNode.getId()==cluster.getCurrentServerNodeId()){//当前服务器节点
				   if("azureStorage".equals(appInstance.getStorageType())){//微软云远程实例
					    saveToAzureStorage(localFilePath, relativeFilePath,fileName,serverNode, appInstance);
				   }else if("local".equals(appInstance.getStorageType())){
				      if(!localFilePath.contains(appInstance.getFtpHomeDirectory()+"/")){//本地非事件触发实例
					    saveToLocal(localFilePath, relativeFilePath,fileName,serverNode, appInstance);
				      }
				   }
			   }else{
				   if("azureStorage".equals(appInstance.getStorageType())){//微软云远程实例
					    saveToAzureStorage(localFilePath, relativeFilePath,fileName,serverNode, appInstance);
				   }else{
				        saveToRomote(localFilePath, relativeFilePath,fileName,serverNode, appInstance);
				   }
			   }
		   }
    }
}

private static void saveToRomote(String localFilePath,String relativeFilePath,String fileName,ServerNode serverNode, AppInstance appInstance) throws SocketException,IOException {
    log.info("即将在远程主机 "+serverNode.getIp()+" 目录 "+appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+" 中保存文件 "+fileName); 
    FTPClientUtil ftpUtil=new FTPClientUtil();
	ftpUtil.connectServer(serverNode.getIp(),serverNode.getFtpPort(),appInstance.getFtpUserName(), appInstance.getFtpPassword(), null);
	String[] ssa=relativeFilePath.split("/");
	for(String dir:ssa){
		ftpUtil.createDirectory(dir);
	   	ftpUtil.changeDirectory(dir);
	}
	ftpUtil.uploadFile(localFilePath,fileName);
	ftpUtil.closeServer();
}

private static void saveToLocal(String localFilePath,String relativeFilePath,String fileName,ServerNode serverNode, AppInstance appInstance) throws SocketException,IOException {
    log.info("即将在本机 "+serverNode.getIp()+" 目录 "+appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+" 中保存文件 "+fileName); 
    String desFile=appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+"/"+fileName;
    ExtendedFileUtils.makeDirs(relativeFilePath);
    ExtendedFileUtils.copyFile(new File(localFilePath), new File(desFile));
}


private static void deleteFromLocal(String localFilePath,String relativeFilePath,String fileName,ServerNode serverNode, AppInstance appInstance) throws SocketException,IOException {
	log.info("即将在本机 "+serverNode.getIp()+" 目录 "+appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+" 中删除文件 "+fileName); 
	String desFile=appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+"/"+fileName;
	ExtendedFileUtils.deleteQuietly(new File(desFile));
}

private static void deleteFromAzureStorage(String relativeFilePath,String fileName,ServerNode serverNode, AppInstance appInstance) throws SocketException,IOException {
    String desRelativeFilePathFile=appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+"/";
   	log.info("即将在微软云 目录 "+desRelativeFilePathFile+" 中删除文件 "+fileName); 
	desRelativeFilePathFile=desRelativeFilePathFile.replaceFirst("/","");
    AzureStorageUtil.deleteFile( desRelativeFilePathFile, fileName);
}

private static void saveToAzureStorage(String localFilePath,String relativeFilePath,String fileName,ServerNode serverNode, AppInstance appInstance) throws SocketException,IOException {
    String desRelativeFilePathFile=appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+"/";
   	log.info("即将在微软云 目录 "+desRelativeFilePathFile+" 中保存文件 "+fileName); 
	desRelativeFilePathFile=desRelativeFilePathFile.replaceFirst("/","");
	String[] ssa=desRelativeFilePathFile.split("/");
	StringBuffer tempDir=new StringBuffer();
	for(String dir:ssa){
		tempDir.append(dir).append("/");
		log.info("微软云创建目录子目录"+tempDir.toString());
		AzureStorageUtil.createDirectory(tempDir.toString());
	}
  
    AzureStorageUtil.uploadFile(localFilePath, desRelativeFilePathFile, fileName);
}

private static void deleteFromRomote(String localFilePath,String relativeFilePath,String fileName,ServerNode serverNode, AppInstance appInstance) throws SocketException,IOException {
	log.info("即将在主机 "+serverNode.getIp()+" 目录 "+appInstance.getFtpHomeDirectory()+"/"+relativeFilePath+" 中删除文件 "+fileName); 
	FTPClientUtil ftpUtil=new FTPClientUtil();
	ftpUtil.connectServer(serverNode.getIp(),serverNode.getFtpPort(),appInstance.getFtpUserName(), appInstance.getFtpPassword(), null);
	ftpUtil.changeDirectory(relativeFilePath);
	ftpUtil.deleteFile(fileName);
	ftpUtil.closeServer();
}
public static void deleteFromCluster(String localFilePath) throws SocketException, IOException{
	Cluster cluster=ClusterConfigUtil.getCluster();
	List<ServerNode> serverNodeList=cluster.getServerNodeList();
	String ftpHomeDirectory=getFtpHomeDirectoryBylocalFilePath(localFilePath,cluster.getCurrentServerNodeId())+"/";
    String relativeFilePath=localFilePath.replace(ftpHomeDirectory,"");
	String fileName=relativeFilePath.substring( relativeFilePath.lastIndexOf("/")+1,relativeFilePath.length());
    relativeFilePath=relativeFilePath.substring(0,relativeFilePath.lastIndexOf("/"));
	for(ServerNode serverNode:serverNodeList){
		   List<AppInstance> appInstanceList=serverNode.getAppInstanceList();
		   for(AppInstance appInstance:appInstanceList){
			   
			   if(serverNode.getId()==cluster.getCurrentServerNodeId()){//当前服务器节点
				   if("azureStorage".equals(appInstance.getStorageType())){
					   deleteFromAzureStorage(relativeFilePath,fileName,serverNode, appInstance);
				   }else if("local".equals(appInstance.getStorageType())){
				     if(!localFilePath.contains(appInstance.getFtpHomeDirectory()+"/")){//不是事件触发实例
					 deleteFromLocal(localFilePath, relativeFilePath,fileName,serverNode, appInstance);
				     }
				   }
			   }else{
				   if("azureStorage".equals(appInstance.getStorageType())){
					   deleteFromAzureStorage(relativeFilePath,fileName,serverNode, appInstance);
				   }else{
				       deleteFromRomote(localFilePath, relativeFilePath,fileName,serverNode, appInstance);
				   }
			   }
			  
		   }
    }
}

}
